import re

def parse_markdown_to_json(markdown_file):
    plugins = []
    current_plugin = {}
    plugin_id = 0
    
    with open(markdown_file, 'r', encoding='utf-8') as f:
        content = f.read()
        
    # 分割成段落
    sections = content.split('###')[1:]  # 跳过文件开头的部分
    
    for section in sections:
        if not section.strip():
            continue
            
        lines = section.strip().split('\n')
        if not lines:
            continue
            
        # 获取插件名称和ID
        title_match = re.match(r'\s*(\d+)\.\s+(.+)', lines[0])
        if not title_match:
            continue
            
        plugin_id = int(title_match.group(1))
        name = title_match.group(2).strip()
        
        # 初始化插件数据
        current_plugin = {
            'id': plugin_id,
            'name': name,
            'category': '',
            'description': '',
            'apis': [],
            'targetUsers': [],
            'complexity': 'medium'  # 默认值
        }
        
        # 解析其他字段
        description_found = False
        apis_found = False
        users_found = False
        
        for line in lines[1:]:
            line = line.strip()
            
            # 跳过空行
            if not line:
                continue
                
            # 解析功能描述
            if '功能描述' in line:
                description = line.split('：')[-1].strip()
                current_plugin['description'] = description
                description_found = True
                
            # 解析API能力
            elif '使用能力' in line:
                apis_found = True
                continue
            elif apis_found and line.startswith('- '):
                api = re.search(r'(\w+)\s*API', line)
                if api:
                    current_plugin['apis'].append(api.group(1))
                    
            # 解析目标用户
            elif '目标用户' in line:
                users_text = line.split('：')[-1].strip()
                # 处理可能的不同分隔符
                if '，' in users_text:
                    users = users_text.split('，')
                elif ',' in users_text:
                    users = users_text.split(',')
                elif '、' in users_text:
                    users = users_text.split('、')
                else:
                    users = [users_text]
                current_plugin['targetUsers'] = [u.strip() for u in users if u.strip()]
                users_found = True
        
        # 根据插件ID确定类别
        if plugin_id <= 10:
            current_plugin['category'] = '工作效率类'
        elif plugin_id <= 20:
            current_plugin['category'] = '学习辅助类'
        elif plugin_id <= 30:
            current_plugin['category'] = '开发调试类'
        elif plugin_id <= 40:
            current_plugin['category'] = '数据分析类'
        elif plugin_id <= 50:
            current_plugin['category'] = '社交互动类'
        elif plugin_id <= 60:
            current_plugin['category'] = '生活便利类'
        elif plugin_id <= 70:
            current_plugin['category'] = '安全隐私类'
        elif plugin_id <= 80:
            current_plugin['category'] = '娱乐体验类'
        elif plugin_id <= 90:
            current_plugin['category'] = '教育培训类'
        else:
            current_plugin['category'] = '其他类'
        
        # 根据API数量确定复杂度
        if len(current_plugin['apis']) <= 2:
            current_plugin['complexity'] = 'easy'
        elif len(current_plugin['apis']) >= 5:
            current_plugin['complexity'] = 'hard'
        else:
            current_plugin['complexity'] = 'medium'
            
        plugins.append(current_plugin)
    
    return plugins

def generate_js_content(plugins):
    # 创建JavaScript对象字符串，不使用JSON.dumps以避免字段名带引号
    js_lines = ['const pluginsData = {']
    js_lines.append('  plugins: [')
    
    for i, plugin in enumerate(plugins):
        js_lines.append('    {')
        js_lines.append(f'      id: {plugin["id"]},')
        js_lines.append(f'      name: "{plugin["name"]}",')
        js_lines.append(f'      category: "{plugin["category"]}",')
        js_lines.append(f'      description: "{plugin["description"]}",')
        
        # 处理APIs数组
        apis_str = ', '.join(f"'{api}'" for api in plugin['apis'])
        js_lines.append(f'      apis: [{apis_str}],')
        
        # 处理targetUsers数组
        users_str = ', '.join(f"'{user}'" for user in plugin['targetUsers'])
        js_lines.append(f'      targetUsers: [{users_str}],')
        
        js_lines.append(f'      complexity: "{plugin["complexity"]}"')
        js_lines.append('    }' + (',' if i < len(plugins) - 1 else ''))
    
    js_lines.append('  ]')
    js_lines.append('};')
    js_lines.append('')
    js_lines.append('export default pluginsData;')
    
    return '\n'.join(js_lines)

def main():
    input_file = 'CHROME_PLUGIN_IDEAS.md'
    output_file = 'website/js/plugins-data1.js'
    
    # 解析Markdown文件
    plugins = parse_markdown_to_json(input_file)
    
    # 生成JavaScript文件内容
    js_content = generate_js_content(plugins)
    
    # 写入JavaScript文件
    with open(output_file, 'w', encoding='utf-8') as f:
        f.write(js_content)
    
    print(f'Successfully converted {input_file} to {output_file}')

if __name__ == '__main__':
    main()
